package net.wicp.tams.common.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.json.JSONUtil;

public abstract class J2EEAssist {

	/**
	 * 得到请求中的payload数据
	 * 
	 * @param req
	 * @return
	 */
	public static String getRequestPayload(HttpServletRequest req) {
		try {
			StringBuilder sb = new StringBuilder();
			BufferedReader reader = req.getReader();
			char[] buff = new char[1024];
			int len;
			while ((len = reader.read(buff)) != -1) {
				sb.append(buff, 0, len);
			}
			return URLDecoder.decode(sb.toString(),"UTF-8");
		} catch (Exception e) {
			return null;
		}
	}

	/***
	 * 通过response得到输出流
	 * 
	 * @param response
	 *            响应信息
	 * @param fileName
	 *            导出excel文件的名字
	 * @param isclear
	 *            清空输出流
	 * @return 输出流
	 */
	public static OutputStream getExcelOS(HttpServletResponse response, String fileName, boolean isclear) {
		try {
			OutputStream os = response.getOutputStream();
			if (isclear) {
				response.reset();// 清空输出流
			}
			response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");// 设定输出文件头
			response.setContentType("application/msexcel");// 定义输出类型
			return os;
		} catch (IOException e) {
			return null;
		}
	}

	/***
	 * 返回json数据
	 * 
	 * @param response
	 * @param jsonMsg
	 */
	public static void returnJsonResponse(HttpServletResponse response, String jsonMsg) {
		response.setContentType("text/html");
		try {
			PrintWriter out = response.getWriter();
			out.print(jsonMsg);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void resWithJson(HttpServletResponse response, Result ret) {
		// 将实体对象转换为JSON Object转换
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			JSONObject retjson = JSONUtil.setResult(ret);
			out.append(retjson.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	/***
	 * 返回json数据
	 * 
	 * @param response
	 * @param optResult
	 *            要返回的结果封装
	 */
	public static void returnJsonResponse(HttpServletResponse response, Result optResult) {
		returnJsonResponse(response, optResult.retJsonObj().toJSONString());
	}

}
